package org.zjt.rabbit.demo.delay;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.rabbitmq.client.*;
import org.zjt.rabbit.demo.common.ContantsConfig;

/**
 * 延时任务： 一般使用MQ来实现，不用redis来实现。因为redis会丢数据。（redis订阅key超时事件）
 */
public class Consumer {

    // 目的队列
    private final static String DESTINATION_QUEUE_NAME = "DESTINATION_QUEUE_NAME";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(ContantsConfig.MQ_HOST);
        factory.setUsername(ContantsConfig.USER);
        factory.setPassword(ContantsConfig.PASSWORD);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(DESTINATION_QUEUE_NAME, false, false, false, null);
        System.out.println("C [*] Waiting for messages. To exit press CTRL+C");

        com.rabbitmq.client.Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("C [x] Received '" + message + "'");
            }
        };
        channel.basicConsume(DESTINATION_QUEUE_NAME, true, consumer);

    }
}